package guda.mrpc.core.codec;

import guda.mrpc.core.serialize.ObjectSerialize;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * Created by well on 17/5/23.
 */
public class ObjectEncoder  extends MessageToByteEncoder {

    private ObjectSerialize objectSerialize;
    private Class<?> genericClass;

    public ObjectEncoder(ObjectSerialize objectSerialize, Class<?> genericClass) {
        this.objectSerialize = objectSerialize;
        this.genericClass = genericClass;
    }

    @Override
    public void encode(ChannelHandlerContext ctx, Object in, ByteBuf out) throws Exception {
        if (genericClass.isInstance(in)) {
            byte[] data = objectSerialize.serialize(in);
            out.writeInt(data.length);
            out.writeBytes(data);
        }
    }
}
